package com.caigou.modules.tools.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.BuyFlowerDialog
import com.caigou.comm.base.widget.TipsDialog
import com.caigou.modules.tools.R
import com.caigou.modules.tools.bean.CardBean
import com.caigou.modules.tools.databinding.FragmentCardBinding
import com.caigou.modules.tools.viewmodel.ToolsViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/10/14
 */
@AndroidEntryPoint
class CardFragment : BaseFragment() {

    private var _binding: FragmentCardBinding? = null
    private val binding get() = _binding!!
    private val toolViewModel: ToolsViewModel by viewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentCardBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.cardSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                toolViewModel.getCardList(AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        binding.cardCvRename.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Center.PAGE_DETAIL)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Center.TAG_RENAME_CARD)
                .navigation()
        }

        binding.cardCvDelete.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Center.PAGE_DETAIL)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Center.TAG_DELETE_CARD)
                .navigation()
        }

        binding.cardCvFlower.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Center.PAGE_DETAIL)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Center.TAG_FLOWER)
                .navigation()
        }

        binding.cardCvFree.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Center.PAGE_DETAIL)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Center.TAG_FREE_CARD)
                .navigation()
        }

        binding.cardLayoutRenameCard.renameCardBtnExchange.setOnClickListener {
            val dialog = TipsDialog(requireActivity(), true)
            dialog.apply {
                tvTitle.text = "提示"
                tvContent.text = "您将消耗1000朵小红花，兑换一张改名卡"
                tvLeft.text = "取消"
                dialog.tvLeft.setOnClickListener {
                    dismiss()
                }
                tvRight.text = "立即兑换"
                tvRight.setOnClickListener {
                    toolViewModel.exchangeRenameCard(AppBackgroundInfo.instance.userBean!!.userId)
                    dismiss()
                }
                show()
            }
        }

        binding.cardLayoutDeleteCard.deleteCardBtnExchange.setOnClickListener {
            val dialog = TipsDialog(requireActivity(), true)
            dialog.apply {
                tvTitle.text = "提示"
                tvContent.text = "您将消耗20朵小红花，兑换一张删除卡"
                tvLeft.text = "取消"
                dialog.tvLeft.setOnClickListener {
                    dismiss()
                }
                tvRight.text = "立即兑换"
                tvRight.setOnClickListener {
                    toolViewModel.exchangeDeleteCard(AppBackgroundInfo.instance.userBean!!.userId)
                    dismiss()
                }
                show()
            }
        }

        binding.cardLayoutFlowerCard.flowerCardBtnExchange.setOnClickListener {
            val dialog = BuyFlowerDialog(requireActivity())
            dialog.apply {
                btnConfirm.setOnClickListener {
                    toolViewModel.buyFlower(AppBackgroundInfo.instance.userBean!!.userId, flowerNum)
                    dismiss()
                }
                show()
            }
        }

        binding.cardTvBack.setOnClickListener {
            (requireActivity() as ToolsActivity).onBackPressed()
        }
    }

    override fun lazyLoad() {
        toolViewModel.getCardList(AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(toolViewModel.cardListLiveData, ::handleGetCardList)
        observe(toolViewModel.renameCardLiveData, ::handleExchangeRenameCard)
        observe(toolViewModel.deleteCardLiveData, ::handleExchangeDeleteCard)
        observe(toolViewModel.buyFlowerLiveData, ::handleBuyFlower)
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetCardList(status: Resource<CardBean>) {
        when (status) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.cardSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(status.errorMsg)) {
                    showToast(status.errorMsg)
                } else {
                    showToast("获取卡包信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.cardSwipeRefreshLayout.isRefreshing = false
                if (status.data == null) {
                    return
                }
                binding.cardLayoutRenameCard.renameCardTvNum.text = "数量：${status.data!!.renameCardNumber}"
                binding.cardLayoutDeleteCard.deleteCardTvNum.text = "数量：${status.data!!.deleteCardNumber}"
                binding.cardLayoutFlowerCard.flowerCardTvNum.text = "数量：${status.data!!.flowerNumber}"
                binding.cardLayoutFreeCard.freeCardTvNum.text = "数量：${status.data!!.freeGoldCardNumber}"
            }
        }
    }

    private fun handleExchangeRenameCard(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("兑换改名卡异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun handleExchangeDeleteCard(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("兑换删除卡异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun handleBuyFlower(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("购买小红花异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }
}